import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';
import { fetchValidation } from '@/utils';
import {
  queryDetailInfo,
  operSaveOrUpdate,
  operVerPhone,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    saveOrUpdate: Effect;
    verPhone: Effect;
  };
  reducers: {
    save: Reducer;
    saveInfo: Reducer;
    clear: Reducer;
  };
}

const stateInfo = {
  detailInfo: {},
  userInfo: {},
};

const Model: ModelType = {
  namespace: 'couriersMangagementSaveOrUpdate',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryDetailInfo, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: data.body,
      });
    },

    * saveOrUpdate({ payload }, { call, put }) {
      const formData = new FormData();
      Object.entries(payload).map((item: any) => (
        formData.append(item[0], item[1])
      ));
      const response = yield call(operSaveOrUpdate, formData);
      const data = fetchValidation(response);
      if (data) {
        message.success(payload.userId ? '修改成功' : '添加成功');
        yield put({
          type: 'global/setPath',
        });
        router.goBack();
      }
    },

    * verPhone({ payload }, { call, put }) {
      const response = yield call(operVerPhone, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveInfo',
        payload: data.body,
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        detailInfo: payload,
      };
    },

    saveInfo(state, { payload }) {
      return {
        ...state,
        userInfo: payload,
      };
    },

    clear() {
      return stateInfo;
    },
  },
};

export default Model;
